package com.mf.morefun.ui.person.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.apkfuns.logutils.LogUtils;
import com.mf.morefun.R;
import com.mf.morefun.adapter.BookMarkAdapter;
import com.mf.morefun.adapter.ListenAdapter;
import com.mf.morefun.adapter.WorksListAdapter;
import com.mf.morefun.base.BaseBusFragment;
import com.mf.morefun.bean.BookMarkListBean;
import com.mf.morefun.bean.ListenBean;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.bean.WorksBean;
import com.mf.morefun.bean.WorksListBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.requestbean.RequestBookMarkBean;
import com.mf.morefun.requestbean.RequestListenBean;
import com.mf.morefun.requestbean.RequestWorksBean;
import com.mf.morefun.ui.VideoActivity;
import com.mf.morefun.ui.dohomework.HomeworkListActivity;
import com.mf.morefun.ui.moreread.ListenOriginalActivity;
import com.mf.morefun.ui.moreread.ListenRecordActivity;
import com.mf.morefun.ui.moreread.ListenTeacherActivity;
import com.mf.morefun.ui.moreread.MoreReadDetailActivity;
import com.mf.morefun.ui.moreread.TestActivity;
import com.mf.morefun.util.HaveTestUtil;
import com.mf.morefun.widget.NetErrorPop;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhcx.zhcxlibrary.utils.DeviceUtils;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import butterknife.BindView;

public class BookMarkFragment extends BaseBusFragment {
    @BindView(R.id.gv_bookmark)
    GridView gvBookmark;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private ClassicsHeader mClassicsHeader = null;
    private int pageNo = 1;
    private SPUtils mSputils;
    private int totlePage = 1;
    private List<BookMarkListBean> mBookMarkList = new ArrayList<>();
    private BookMarkAdapter adapter;
    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_bookmark;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        mSputils = new SPUtils(getActivity());
        mClassicsHeader = (ClassicsHeader)refreshLayout.getRefreshHeader();
        int delda = new Random().nextInt(7 * 24 * 60 * 60 * 1000);
        mClassicsHeader.setLastUpdateTime(new Date(System.currentTimeMillis() - delda));
        mClassicsHeader.setTimeFormat(new SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA));
        refreshLayout.getLayout().bringChildToFront(gvBookmark);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNo = 1;
                initBookMarkList(true);
                refreshLayout.setEnableLoadMore(true);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageNo ++;
                if (pageNo < totlePage){
                    initBookMarkList(false);
                }else {
                    if (null != refreshLayout){
                        refreshLayout.finishLoadMore();
                        refreshLayout.finishRefresh();
                        refreshLayout.setEnableLoadMore(false);
                    }
                }
            }
        });
        gvBookmark.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //点击
                if (null != mBookMarkList && mBookMarkList.size() > 0){
                    if (null != mBookMarkList.get(position).getBook()){
                        if (null != mBookMarkList.get(position).getBook().getMfVideoList() && mBookMarkList.get(position).getBook().getMfVideoList().size() > 0){
                            //看视频
                            Intent mIntent = new Intent(getActivity(), VideoActivity.class);
                            mIntent.putExtra("VIDEO", mBookMarkList.get(position).getBook().getMfVideoList().get(0).getAddress());
                            mIntent.putExtra("BOOKID", mBookMarkList.get(position).getBook().getId());
                            mIntent.putExtra(Configuration.USERID, mSputils.getString(Configuration.USERID));
                            startActivity(mIntent);
                        }else {
                            showDetailDialog(position);
                        }
                    }else {
                        showDetailDialog(position);
                    }
                }
            }
        });
    }

    //点击弹出可以
    private void showDetailDialog(int position) {
        final Dialog dialog = new Dialog(getActivity(), R.style.loginerrordialog);
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_dialogdetail, null);
        dialog.setContentView(view);
        LinearLayout ll_explain = view.findViewById(R.id.ll_explain);
        LinearLayout ll_fundamental = view.findViewById(R.id.ll_fundamental);
        LinearLayout ll_recording = view.findViewById(R.id.ll_recording);
        LinearLayout ll_test = view.findViewById(R.id.ll_test);
        TextView tv_recording = view.findViewById(R.id.tv_recording);
        tv_recording.setText("录音");
        if (StringUtils.isEmpty(mBookMarkList.get(position).getBook().getHaveListenFlag())){
            ll_explain.setBackgroundResource(R.drawable.gray_shape);
        }else {
            if (mBookMarkList.get(position).getBook().getHaveListenFlag().equals("1")) {
                ll_explain.setBackgroundResource(R.drawable.blue_shape);
            } else {
                ll_explain.setBackgroundResource(R.drawable.gray_shape);
            }
        }
        if (StringUtils.isEmpty(mBookMarkList.get(position).getBook().getHaveTestFlag())){
            ll_test.setBackgroundResource(R.drawable.gray_shape);
        }else {
            if (mBookMarkList.get(position).getBook().getHaveTestFlag().equals("1")) {
                ll_test.setBackgroundResource(R.drawable.blue_shape);
            } else {
                ll_test.setBackgroundResource(R.drawable.gray_shape);
            }
        }
        initListener(position, ll_explain, ll_fundamental, ll_recording, ll_test, dialog);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);
        dialog.show();
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (DeviceUtils.deviceWidth(mContext) * 0.8);
        lp.height = (int) (DeviceUtils.deviceWidth(mContext) * 0.22);
        dialogWindow.setAttributes(lp);
    }

    private void initListener(int position, LinearLayout ll_explain, LinearLayout ll_fundamental, LinearLayout ll_recording, LinearLayout ll_test, Dialog dialog) {
        ll_explain.setOnClickListener(new View.OnClickListener() {//听讲解
            @Override
            public void onClick(View v) {
                if (StringUtils.isEmpty(mBookMarkList.get(position).getBook().getHaveListenFlag())){
                    ToastUtils.show(getActivity(), "当前还没有老师讲解呢！", 100);
                }else {
                    if (mBookMarkList.get(position).getBook().getHaveListenFlag().equals("1")){
                        dialog.dismiss();
                        //调接口
                        initGetListen(mBookMarkList.get(position).getBook().getId());
                    }else {
                        ToastUtils.show(getActivity(), "当前还没有老师讲解呢！", 100);
                    }
                }
            }
        });
        ll_fundamental.setOnClickListener(new View.OnClickListener() {//听原音
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(getActivity(), ListenOriginalActivity.class);
                mIntent.putExtra("BOOKID", mBookMarkList.get(position).getBook().getId());
                mIntent.putExtra("BOOKNAME", mBookMarkList.get(position).getBook().getName());
                mIntent.putExtra(Configuration.USERID, mSputils.getString(Configuration.USERID));
                startActivity(mIntent);
            }
        });
        ll_recording.setOnClickListener(new View.OnClickListener() {//录音
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(getActivity(), ListenRecordActivity.class);
                mIntent.putExtra("BOOKID", mBookMarkList.get(position).getBook().getId());
                mIntent.putExtra("BOOKNAME", mBookMarkList.get(position).getBook().getName());
                mIntent.putExtra("TYPE", "1");
                mIntent.putExtra("CONTEXTTYPE", "1");
                mIntent.putExtra("MEDIATYPE", "1");
                mIntent.putExtra("CONTEXTID", mBookMarkList.get(position).getBook().getId());
                mIntent.putExtra(Configuration.USERID, mSputils.getString(Configuration.USERID));
                startActivity(mIntent);
            }
        });
        ll_test.setOnClickListener(new View.OnClickListener() {//测试
            @Override
            public void onClick(View v) {
                if (StringUtils.isEmpty(mBookMarkList.get(position).getBook().getHaveTestFlag())){
                    ToastUtils.show(getActivity(), "当前绘本还没有测试题！", 100);
                }else {
                    if (mBookMarkList.get(position).getBook().getHaveTestFlag().equals("1")) {
                        HaveTestUtil mHave = new HaveTestUtil();
                        mHave.initGetTest(getActivity(), mBookMarkList.get(position).getBook().getId(), mSputils.getString(Configuration.USERID));
                    }else {
                        ToastUtils.show(getActivity(), "当前绘本还没有测试题！", 100);
                    }
                }
            }
        });
    }

    private void initGetListen(String bookId) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.LISTENTEACHER);
        RequestListenBean requestListenBean = new RequestListenBean();
        RequestListenBean.BookBean bookBean = new RequestListenBean.BookBean();
        bookBean.setId(bookId);
        requestListenBean.setBook(bookBean);
        params.setBodyContent(JSON.toJSONString(requestListenBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        if (!StringUtils.isEmpty(resultBean.getResult())) {
                            List<ListenBean> listenBeanList = JSON.parseArray(resultBean.getResult(), ListenBean.class);
                            if (null != listenBeanList && listenBeanList.size() > 0){
                                try {
                                    showExplainPop(listenBeanList);
                                }catch (Exception e){
                                    e.printStackTrace();
                                }

                            }
                        } else {
                            ToastUtils.show(getActivity(), "数据为空", 100);
                        }
                    } else {
                        ToastUtils.show(getActivity(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    private PopupWindow mExplainPop = null;
    private void showExplainPop(List<ListenBean> listenBeanList) {
        closePop();
        if (mExplainPop == null) {
            LayoutInflater inflater = getLayoutInflater();
            View view = inflater.inflate(R.layout.layout_popexplain, null);
            // 这里启动头像
            RelativeLayout rl_bg = (RelativeLayout) view.findViewById(R.id.rl_bg);
            rl_bg.getBackground().setAlpha(100);
            ListView lv_explain = view.findViewById(R.id.lv_explain);
            ListenAdapter adapter = new ListenAdapter(getActivity(), listenBeanList);
            lv_explain.setAdapter(adapter);
            lv_explain.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //开始听讲解
                    Intent mIntent = new Intent(getActivity(), ListenTeacherActivity.class);
                    mIntent.putExtra("BOOKNAME", listenBeanList.get(position).getName());
                    mIntent.putExtra("LISTENBEAN", listenBeanList.get(position));
                    mIntent.putExtra(Configuration.USERID, mSputils.getString(Configuration.USERID));
                    startActivity(mIntent);
                    closePop();
                }
            });
            TextView tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
            tv_cancel.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    closePop();
                }
            });
            int h = getActivity().getWindowManager().getDefaultDisplay().getHeight();
            mExplainPop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, h);
            mExplainPop.setFocusable(true);
            mExplainPop.setOutsideTouchable(true);
            mExplainPop.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    // 这里如果返回true的话，touch事件将被拦截
                    // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
                    return false;
                }
            });
            mExplainPop.setBackgroundDrawable(new BitmapDrawable());
            Rect rect = new Rect();
            getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
            int winHeight = getActivity().getWindow().getDecorView().getHeight();
            mExplainPop.showAtLocation(getActivity().getWindow().getDecorView(), Gravity.BOTTOM, 0, winHeight - rect.bottom);
        }
    }

    private void closePop(){
        if (null != mExplainPop){
            mExplainPop.dismiss();
            mExplainPop = null;
        }
    }


    @Override
    protected void initData() {
        adapter = new BookMarkAdapter(getActivity(), mBookMarkList);
        gvBookmark.setAdapter(adapter);
        initBookMarkList(true);
    }

    private void initBookMarkList(boolean isRefresh) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.BOOKMARKLIST);
        RequestBookMarkBean requestWorksBean = new RequestBookMarkBean();
        requestWorksBean.setPageNo(pageNo);
        requestWorksBean.setPageSize(20);
        requestWorksBean.setOrderBy(" a.update_date desc");
        RequestBookMarkBean.MfBookmarkBean workBean = new RequestBookMarkBean.MfBookmarkBean();
        RequestBookMarkBean.MfBookmarkBean.UserBean userBean = new RequestBookMarkBean.MfBookmarkBean.UserBean();
        userBean.setId(mSputils.getString(Configuration.USERID));
        workBean.setUser(userBean);
        requestWorksBean.setMfBookmark(workBean);
        params.setBodyContent(JSON.toJSONString(requestWorksBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (null != refreshLayout){
                    refreshLayout.finishLoadMore();
                    refreshLayout.finishRefresh();
                }
                if (isRefresh){
                    mBookMarkList.clear();
                }
                LogUtils.d(result);
                if (!StringUtils.isEmpty(result)){
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0){
                        if (!StringUtils.isEmpty(resultBean.getResult())){
                            WorksBean worksBean = JSON.parseObject(resultBean.getResult(), WorksBean.class);
                            if (!StringUtils.isEmpty(worksBean.getList())){
                                List<BookMarkListBean> BookMarkListBeanList = JSON.parseArray(worksBean.getList(), BookMarkListBean.class);
                                mBookMarkList.addAll(BookMarkListBeanList);
                            }
                            totlePage = worksBean.getTotalPage();
                        }else {
                            ToastUtils.show(getActivity(), "数据为空", 100);
                        }
                    }
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (null != refreshLayout){
                    refreshLayout.finishLoadMore();
                    refreshLayout.finishRefresh();
                }
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(getActivity());
                    errorPop.showPop("");
                    break;
            }
        }
    };
}
